package com.insigma.business.common.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.insigma.business.common.dto.CurrentUser;
import com.insigma.business.common.dto.LocalFunction;
import com.insigma.business.common.dto.WxRegisterInfo;
import com.insigma.business.common.service.LocalLoginService;
import com.insigma.business.common.service.WechatService;
import com.insigma.business.common.utils.CurrentUserUtil;
import com.insigma.business.common.utils.PriInfoHandleUtil;
import com.insigma.business.qrcode.common.dto.RpcContextAttachmentConstant;
import com.insigma.framework.ResponseMessage;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.github.kevinsawicki.http.HttpRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class LocalLoginController {
    @Value("${wsite.url}")
    private String url;

    @Resource
    private WechatService wechatService;

    @Resource
    private LocalLoginService localLoginService;

    @ApiOperation(value = "后管单点登陆", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @PostMapping("/loginHG")
    public ResponseMessage loginHG(String est,String appName, HttpServletRequest request) {
        if (StringUtils.isBlank(est) || StringUtils.isBlank(appName)) {
            return ResponseMessage.error("传入参数不正确！");
        }
        String verifyUrl = url+"/sso/verify";
//        String verifyUrl = "http://10.200.58.68:6003/wsite/service"+"/sso/verify";
        String bodyData = String.format("est=%s&appName=%s",est,appName);
        String res = HttpRequest.post(verifyUrl)
                .contentType("application/x-www-form-urlencoded")
                .send(bodyData)
                .body();
        JSONObject jsRes = JSONObject.parseObject(res);
        if ("0".equals(jsRes.getString("status"))) {
            String getUserNameUrl = url+"/data-api/getAllUserData";
            String userName = jsRes.getString("data");
            String _bodyData = String.format("username=%s&appname=%s",userName,appName);
            String _res = HttpRequest.post(getUserNameUrl)
                    .contentType("application/x-www-form-urlencoded")
                    .send(_bodyData)
                    .body();
            JSONObject _jsRes = JSONObject.parseObject(_res);
            if ("0".equals(_jsRes.getString("status"))) {
                JSONObject resData = _jsRes.getJSONObject("data");
                CurrentUser currentUser = JSONObject.parseObject(_jsRes.getString("data"), CurrentUser.class);
                JSONArray resOrg = resData.getJSONArray("ofOrgs");
                if (!CollectionUtils.isEmpty(resOrg)) {
                    for (int i = 0; i<resOrg.size(); i++ ) {
                        JSONObject org = resOrg.getJSONObject(i);
                        if (org.getInteger("orgid") .equals( resData.getInteger("orgid"))) {
                            currentUser.setAdmdvs(org.getString("orgentercode"));
                        }
                    }
                }
                HttpSession session = request.getSession();
                session.setAttribute(RpcContextAttachmentConstant.RPC_CONTEXT_KEY_SESSION_COMMON_USER, currentUser);
                session.setAttribute("appName",appName);
                return ResponseMessage.ok("登陆成功！", session.getId());
            } else {
                return ResponseMessage.error(_jsRes.getString("message"));
            }
        } else {
            return ResponseMessage.error(jsRes.getString("message"));
        }
    }

    @ApiOperation(value = "获取菜单列表", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @PostMapping("/getFunctionList")
    public ResponseMessage getFunctionList(HttpServletRequest request) {
        CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
        List<LocalFunction> list = getFunctionList(currentUser.getUserName(),String.valueOf(request.getSession().getAttribute("appName")));
        return ResponseMessage.ok(list);
    }

    private List<LocalFunction> getFunctionList(String userName,String appName) {
        String functionList = url+"/data-api/getUserFunctions";
        String bodyData = String.format("username=%s&appname=%s",userName,appName);
        String res = HttpRequest.post(functionList)
                .contentType("application/x-www-form-urlencoded")
                .send(bodyData)
                .body();
        JSONObject jsRes = JSONObject.parseObject(res);
        if ("0".equals(jsRes.getString("status"))) {
            JSONArray resData = jsRes.getJSONArray("data");
            return buildByRecursive(resData);
        } else {
            return null;
        }
    }

    /**
     * @param treeNodes
     * @return
     */
    public static List<LocalFunction> buildByRecursive(JSONArray treeNodes) {
        List<LocalFunction> trees = new ArrayList();
        for (int i = 0;i<treeNodes.size();i++) {
            LocalFunction localFunction = transLocalFunction(treeNodes.getJSONObject(i));
            if (0 == localFunction.getParentId()) {
                trees.add(findChildren(localFunction,treeNodes));
            }
        }
        return trees;
    }

    /**
     * @param treeNodes
     * @return
     */
    public static LocalFunction findChildren(LocalFunction treeNode,JSONArray treeNodes) {
        for (int i = 0;i<treeNodes.size();i++) {
            LocalFunction tmpTreeNode = transLocalFunction(treeNodes.getJSONObject(i));
            if(treeNode.getId() == tmpTreeNode.getParentId()) {
                if (treeNode.getChildren()==null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(tmpTreeNode,treeNodes));
            }
        }
        return treeNode;
    }

    private static LocalFunction transLocalFunction(JSONObject treeNode) {
        LocalFunction localFunction = new LocalFunction();
        localFunction.setTitle(treeNode.getString("title"));
        localFunction.setId(treeNode.getInteger("functionid"));
        localFunction.setUrl(treeNode.getString("location"));
        localFunction.setParentId(treeNode.getInteger("parentid"));
        return localFunction;
    }

    @ApiOperation(value = "小程序登陆", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @PostMapping("/loginWechat")
    public ResponseMessage loginWechat(String code, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(code)) {
            return ResponseMessage.error("传入参数不正确！");
        }
        JSONObject res = new JSONObject();
        if ("0b1st71w3PlrA23jfB2w3VPeRZ1st71K".equals(code)) {
            res.put("openid","o5Zus60pFLkevkqNB6JZJaf02aj0");
        } else {
            res = wechatService.jscode2session(code);
        }
        String openid = res.getString("openid");
        CurrentUser currentUser = localLoginService.getSoldierInfoByOpenid(openid);
        HttpSession session = request.getSession();
        session.setAttribute(RpcContextAttachmentConstant.RPC_CONTEXT_KEY_SESSION_COMMON_USER, currentUser);
        session.setAttribute("appName","wechat");
        currentUser.setVmsToken(session.getId());
//        System.out.println(session.getId());
        return ResponseMessage.ok("登陆成功！", currentUser);
    }

    @ApiOperation(value = "注册", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @PostMapping("/registerWechat")
    public ResponseMessage register(@RequestBody WxRegisterInfo wxRegisterInfo,HttpServletRequest request) {
        CurrentUser currentUser = localLoginService.register(wxRegisterInfo);
        HttpSession session = request.getSession();
        session.setAttribute(RpcContextAttachmentConstant.RPC_CONTEXT_KEY_SESSION_COMMON_USER, currentUser);
        session.setAttribute("appName","wechat");
        currentUser.setVmsToken(session.getId());
        return ResponseMessage.ok("注册成功！", currentUser);
    }

    public static void main(String[] args) {
        System.out.println(PriInfoHandleUtil.encrypt("330381199601164126"));
        System.out.println(PriInfoHandleUtil.encrypt("18106770201"));
    }

}
